/*
 * TCSS 422 - Spring quarter 2011
 * Team: 	Googlers
 * Members: Deepa Sahni, Krisnil Gounder, Michael Schweiger
 * Date: 	April 25, 2011
 */
package web;

import java.io.IOException;
import java.net.URL;
import java.util.Scanner;

import main.Main;

import buffers.Buffer;
import buffers.PageBuffer;

/**
 * A utility class designed to resolve a URL and add the source code (as a
 * string) to the PageBuffer.
 * 
 * @author Michael Schweiger - API framework
 * @version 1.0
 */
public final class PageRetriever implements Runnable {

	/**
	 * The URL to retrieve.
	 */
	private final URL my_URL;

	/**
	 * Constructor that takes the URL. The URL cannot be null.
	 * 
	 * @throws IllegalArgumentException
	 *             if the URL is null.
	 * @param the_URL
	 *            The URL to retrieve.
	 */
	public PageRetriever(final URL the_URL) throws IllegalArgumentException {
		if (the_URL == null) {
			throw new IllegalArgumentException("URL cannot be null!");
		}
		my_URL = the_URL;
	}

	/**
	 * Retrieves the page and returns the source code as a string. If for some
	 * reason, the page cannot be retrieved (bad URL, bad connection, etc), then
	 * an empty string will be returned.
	 * 
	 * @return The HTML source code as a String
	 */
	public String getSource() {
		Scanner input = null;
		try {
			input = new Scanner(my_URL.openStream());
		} catch (IOException e) {
			return "";
		}
		StringBuilder builder = new StringBuilder();
		builder.append(my_URL.toString() + " ");
		while (input.hasNext()) {
			String temp = input.next();
			builder.append(temp + " ");
		}
		return builder.toString();
	}

	/**
	 * Runs the getSource method, putting the source code into the singleton
	 * object PageBuffer.
	 */
	public void run() {
		Buffer<String> buffer = PageBuffer.getInstance();
		buffer.add(getSource());
		Main.finishRetriever();
	}
}
